/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package cn.workreport.util;

import cn.workreport.modules.common.po.PagePO;
import cn.workreport.util.xss.SQLFilter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;

/**
 * 查询参数
 */
public class PageQueryUtil<T> {

    public IPage<T> getPage(PagePO params) {
        return this.getPage(params, null, false);
    }

    public IPage<T> getPage(PagePO params, String defaultOrderField, boolean isDesc) {
        //分页参数
        long curPage = 1;
        long limit = 15;
        String orderField = "created_time";

        if(params.getCurrent() != null){
            curPage = params.getCurrent();
        }
        if(params.getSize() != null){
            limit = params.getSize();
        }
        // 如果两个都为空，则查全部
        if (params.getCurrent() == null && params.getSize() == null) {
            limit = 99999999;
        }
        if(params.getOrderField() != null){
            orderField = params.getOrderField();
        }

        //分页对象
        Page<T> page = new Page<>(curPage, limit);

        //排序字段
        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String orderFieldFill = SQLFilter.sqlInject( orderField );

        //前端字段排序
        if(StringUtils.isNotEmpty(orderFieldFill)) {
            if(params.getAsDesc() == null || params.getAsDesc() == false) {
                return  page.addOrder(OrderItem.asc(orderFieldFill));
            }else {
                return page.addOrder(OrderItem.desc(orderFieldFill));
            }
        }

        //没有排序字段，则不排序
        if(StringUtils.isBlank(defaultOrderField)){
            return page;
        }

        //默认排序
        if(!isDesc) {
            page.addOrder(OrderItem.asc(defaultOrderField));
        }else {
            page.addOrder(OrderItem.desc(defaultOrderField));
        }

        return page;
    }
}
